package com.cn.boot.spring.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 配置类
 * 过滤器
 * 解决跨域问题
 */
@Configuration
@Order(1)
public class FilterConfig {
    private CorsConfiguration buildConfig(){
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedHeader("*"); // 允许任何的head头部
        //springboot 2.4.0以下
//        corsConfiguration.addAllowedOrigin("*"); // 允许任何域名使用
//springboot 2.4.0以上
//corsConfiguration.addAllowedOrigin("具体服务器如:http://192.168.0.110:8801")或者
corsConfiguration.addAllowedOriginPattern("*");
        corsConfiguration.addAllowedMethod("*"); // 允许任何的请求方法
        corsConfiguration.setAllowCredentials(true);//允许前端携带cookie
        return corsConfiguration;
    }
    // 添加CorsFilter拦截器，对任意的请求使用
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}
